/**
 * @version 2007-5-16
 * @author xalinx at gmail dot com
 */
package org.nanhill.commons.dbutil.dialect;

/**
 * @version 2007-5-16
 * @author xalinx at gmail dot com
 * 
 */
public class Oracle9Dialect extends Dialect {

	@Override
	public Object[] getLimitArguments(int start, int size, Object... args) {
		Object[] tmp = null;
		if (start == 0) {
			tmp = new Object[args.length + 1];
			tmp[tmp.length] = start + size;
		} else {
			tmp = new Object[args.length + 2];
			tmp[tmp.length - 1] = start + start;
			tmp[tmp.length] = start;
		}
		System.arraycopy(args, 0, tmp, 0, args.length);
		return tmp;
	}

	@Override
	public String getLimitSql(String sql, boolean hasOffset) {
		sql = sql.trim();
		boolean isForUpdate = false;
		if (sql.toLowerCase().endsWith(" for update")) {
			sql = sql.substring(0, sql.length() - 11);
			isForUpdate = true;
		}

		StringBuffer pagingSelect = new StringBuffer(sql.length() + 100);
		if (hasOffset) {
			pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
		} else {
			pagingSelect.append("select * from ( ");
		}
		pagingSelect.append(sql);
		if (hasOffset) {
			pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?");
		} else {
			pagingSelect.append(" ) where rownum <= ?");
		}

		if (isForUpdate) {
			pagingSelect.append(" for update");
		}

		return pagingSelect.toString();
	}

}
